/*
 * create page
**/
<template>
<div>
<v-tab></v-tab>
<swiper :options="swiperOption" class="page-swiper">
  <swiper-slide v-for="slide in swiperSlides">
    <span :style="{backgroundImage: 'url('+slide.thumb+')'}"></span>
  </swiper-slide>
  <div class="swiper-pagination" slot="pagination"></div>
</swiper>
<div class="mod-block-item">
  <div class="mod-tit"><h3>精品推荐</h3><p><i class="icon-gold"></i> {{ scoreInfo}}</p></div>
  <div class="tit-tips"><em>提示：</em>您所兑换的<em>【微信红包】</em>将在<em>24小时内</em>通过“游戏化赢销”公众号发放到您的微信中，请留意。</div>
  <div class="mod-goods">
    <ul class="clearfix" v-load-more="loaderMore">
      <li class="fl" v-for="item in goodsList">
        <div class="goods-item">
          <div class="bd" :style="{backgroundImage: 'url('+item.icon+')'}"></div>
          <div class="ft">
            <div class="tit">{{item.title}}</div>
            <div class="clearfix">
              <div class="fl"><i class="icon-gold"></i> {{item.point}}</div>
              <div class="fr" v-if="0"><span class="ui-btn btn-gray">立即兑换</span></div>
              <div class="fr"><span class="ui-btn" @click="tryExchange(item.pid, item.point, item.title)">立即兑换</span></div>
            </div>
          </div>
        </div>
      </li>
    </ul>
    <div class="weui-loadmore" v-if="showLoading">
      <i class="weui-loading"></i>
      <span class="weui-loadmore__tips">正在加载</span>
    </div>
    <div class="weui-loadmore weui-loadmore_line" v-if="touchend">
        <span class="weui-loadmore__tips">期待上新</span>
    </div>
  </div>
</div>
<div class="mod-footer-place"></div>
<modal-dialog ref="dialog"></modal-dialog>

<div v-if="showChkMobile" transition="fade">
    <div class="weui-dialog reset-top">
      <div class="weui-dialog-hd"><span style="color:#ffa200;">首次兑换</span>，需要输入手机验证码</div>
      <div class="weui-dialog-bd chk-mobile">
        <div class="form-item">
          <input class="weui-input tc" v-model.number="mobile" type="number" name="" placeholder="请输入手机号" @blur="chkMobile">
          <p v-if="errorMobileInfo" class="red tl">{{errorMobileInfo}}</p>
        </div>
        <div class="form-item form-code-item">
          <div class="code-input"><input class="weui-input tc" v-model.number="code" type="number" name=""></div>
          <span :class="{'weui-btn': true, 'weui-btn_mini': true, 'in-disable': verifyCodeDisabled}" @click="tryGetVerifyCode">{{verifyCodeMsg}}</span>
          <p v-if="errorCodeInfo" class="red tl">{{errorCodeInfo}}</p>
        </div>
      </div>
      <div class="weui-dialog-ft">
        <slot name="button">
          <span class="modal-btn modal-btn-primary full-button" @click="submitChkMobile">提交</span>
        </slot>
      </div>
      <a href="javascript:void(0)" class="dialogCloseBtn" @click="closeChkMobile"></a>
    </div>
    <div class="modal-maks" transition="fade"></div>
</div>


</div>
</template>
<script>
import vTab from 'components/common/tab'
import modalDialog from 'src/components/dialog'
import {loadMore} from 'src/config/mixin'
import {getShop, getUserCredit, shopExchange, ChkSubscribe, shopChkMobile, getBanner, bannerRecord} from '../../service/getData'
import {mapState} from 'vuex'
export default {
  data () {
    return {
      showChkMobile: false,
      mobile: '',
      errorMobileInfo: '',
      verifyCodeTime: 60,  // 验证码倒计时时间
      verifyCodeMsg: '获取',
      verifyCodeDisabled: false,
      code: '',
      errorCodeInfo: '',
      swiperOption: {
        autoplay: 3500,
        setWrapperSize: true,
        // pagination: '.swiper-pagination',
        // paginationClickable: true,
        mousewheelControl: true,
        observeParents: true,
        loop: true,
        // 解决loop时复制出来的元素绑定事件不成功，使用箭头函数，避免解析时获取data属性为undefined
        onClick: (swiper) => {
          let item = this.swiperSlides[swiper.realIndex]
          this.tryBannerRecord(item.aid, item.url)
        }
      },
      swiperSlides: [{}],
      scoreInfo: 0,
      goodsList: [],
      subscribe: true,
      offset: 1, // 批次加载数据 每次+1
      pageSize: 10, // 每页显示数据条数
      preventRepeatReuqest: false, // 到达底部加载数据，防止重复加载
      showLoading: true, // 显示加载动画
      touchend: false // 没有更多数据
    }
  },
  mixins: [loadMore],
  computed: {
    ...mapState([
      'I9RIA'
    ])
  },
  mounted () {
    if (this.I9RIA && this.I9RIA.wxJsApiConf) {
      this.initData()
    }
  },
  components: {
    'v-tab': vTab,
    modalDialog
    // swiper,
    // swiperSlide
  },
  methods: {
    async initData () {
      this.getBannerInfo(1)
      // let res = await ChkSubscribe()
      // if (res.code === 100011) {
      //   this.subscribe = false
      // }
      let tmpDataS = await getUserCredit()  // 获取积分余额
      console.log(tmpDataS)
      let tmpData = await getShop(this.offset) // 获取商品列表
      console.log(tmpData)
      if (tmpDataS.code !== 0) return
      this.scoreInfo = tmpDataS.data.credit_point
      this.showLoading = false
      this.touchend = true
      this.preventRepeatReuqest = false
      if (tmpData.code !== 0) return
      if (tmpData.data.list.length < this.pageSize) {
        this.touchend = true
      } else {
        this.touchend = false
      }
      this.goodsList = tmpData.data.list
    },
    async getBannerInfo (type) {
      let res = await getBanner(type)
      if (res.code !== 0) {
        return
      }
      this.swiperSlides = res.data.list
    },
    async tryBannerRecord (id, url) {
      await bannerRecord(id)
      if (url.indexOf('http') !== -1) {
        window.location.href = url
      } else if (url.indexOf('http') === -1 && url.indexOf('#/') !== -1) {
        let routerUrl = url.substring(1)
        console.log(routerUrl)
        this.$router.push(routerUrl)
      }
    },
    chkMobile () {
      if (!this.mobile) {
        this.errorMobileInfo = '手机号不能为空'
        return
      }
      if (!(/^1[3|4|5|7|8][0-9]\d{8}$/.test(this.mobile))) {
        this.errorMobileInfo = '请输入正确的手机号'
        return
      }
    },
    chkCode () {
      if (!this.code) {
        this.errorCodeInfo = '验证码不能为空'
        return
      }
      if (!(/^\d{6}$/.test(this.code))) {
        this.errorCodeInfo = '验证码格式为6位数字!'
        return
      }
    },
    tryGetVerifyCode () { // 校验手机号
      this.chkMobile()
      if (!this.errorMobileInfo) {
        this.tryChkMobile()
      }
    },
    async tryChkMobile () { // 发送验证码
      if (this.verifyCodeDisabled) {
        return
      }
      this.verifyCodeMsg = '获取中'
      this.verifyCodeDisabled = true
      let res = await shopChkMobile({mobile: this.mobile, step: 1})
      if (res.code !== 0) {
        this.errorMobileInfo = res.msg
        this.verifyCodeMsg = '获取'
        this.verifyCodeDisabled = false
        return
      }
      this.countDowmTime()
      console.log(res)
    },
    countDowmTime () {  // 验证码倒计时
      let timmer = setTimeout(() => {
        this.verifyCodeTime --
        this.verifyCodeMsg = `${this.verifyCodeTime}s`
        if (this.verifyCodeTime > 0) {
          this.countDowmTime()
        } else {
          this.verifyCodeMsg = '获取'
          this.verifyCodeDisabled = false
          clearTimeout(timmer)
        }
      }, 1000)
    },
    async submitChkMobile () {
      this.chkMobile()
      this.chkCode()
      if (this.errorMobileInfo || this.errorCodeInfo) {
        return
      }
      let res = await shopChkMobile({mobile: this.mobile, code: this.code, step: 2})
      if (res.code !== 0) {
        this.errorCodeInfo = res.msg
        return
      }
      this.closeChkMobile()
    },
    closeChkMobile () {
      this.showChkMobile = false
      this.mobile = ''
      this.code = ''
    },
    async tryExchange (id, score, title) {
      let res = await ChkSubscribe()
      if (res.code === 0) {
        this.subscribe = true
      } else {
        this.subscribe = false
      }
      if (!this.subscribe) {
        this.$refs.dialog.confirm('<h3>请先关注 <span style="color:#ffa200;"> 玩赚福利平台</span><br>再进行积分兑换</h3>', {
          type: 'tips',
          okText: '关注'
        }).then(() => {
          this.$refs.dialog.confirm('<h3 class="qrcode"></h3>', {
            type: 'alert',
            isQRcode: true
          })
        })
        return
      }
      if (score > this.scoreInfo * 1) {
        this.$refs.dialog.confirm('<h3 style="color:#ffa200">兑换失败！</h3><h3>您的积分不足</h3>', {
          type: 'alert'
        })
      } else {
        this.$refs.dialog.confirm(`<div>您将消费 <span style="color:#ffa200">${score}积分</span> 兑换</div><h4 style="color:#feb902">“${title}”</h4>`, {
          // title: '<span style="color:#feb902">兑换成功！</span>',
          type: 'confirm'
        }).then(() => {
          this.exchange(id)
        }).catch(() => {
        })
      }
    },
    async exchange (id) {
      let res = await shopExchange(id)
      console.log(res)
      if (res.code === 0 && res.data.credit_point) {
        this.scoreInfo = res.data.credit_point
        this.$refs.dialog.confirm('<h3 style="color:#ffa200">兑换成功！</h3><h3>红包将在24小时内通过<span style="color:#feb902;">“游戏化赢销”</span>公众号发放到您的微信中，请耐心等待~ </h3>', {
          type: 'alert'
        })
      } else if (res.code === 100012) {
        window.location.href = res.data.redirect
      } else if (res.code === 100014) { // 校验验证码
        // 校验手机号
        this.showChkMobile = true
      } else if (res.code === 100011) {
        this.scoreInfo = res.data.credit_point
        this.$refs.dialog.confirm('<h3>请先关注 <span style="color:#ffa200;"> 玩赚福利平台</span><br>再进行积分兑换</h3>', {
          type: 'tips',
          okText: '关注'
        }).then(() => {
          this.$refs.dialog.confirm('<h3 class="qrcode"></h3>', {
            type: 'alert',
            isQRcode: true
          })
        })
      } else {
        this.$refs.dialog.confirm(`<div><h3>${res.msg}</h3></div>`, {
          type: 'tips'
        })
      }
    },
    async loaderMore () {
      if (this.touchend) {
        return
      }
      // 防止重复请求
      if (this.preventRepeatReuqest) {
        return
      }
      this.showLoading = true
      this.preventRepeatReuqest = true

      // 数据的定位+1
      this.offset++
      let res = await getShop(this.offset)
      if (res.code !== 0) {
        this.showLoading = false
        this.touchend = true
        this.preventRepeatReuqest = false
        return
      }
      this.showLoading = false
      this.goodsList = [...this.goodsList, ...res.data.list]
      // 当获取数据小于20，说明没有更多数据，不需要再次请求数据
      if (res.data.list.length < this.pageSize) {
        this.touchend = true
        return
      }
      this.preventRepeatReuqest = false
    }
  },
  watch: {
    I9RIA (res) {
      let val = res || {}
      if (val && val.wxJsApiConf) {
        this.initData()
      }
      if (val.code === 9999) {
        this.$router.push('/404')
      }
    },
    mobile (val) {
      this.errorMobileInfo = ''
      this.code = ''
    },
    code (val) {
      this.errorCodeInfo = ''
    }
  }
}
</script>
<style scoped>
.page-swiper{width:100%; height:0.43rem;}
.swiper-slide,
.swiper-slide span{width:100%; height:100%; display:block;}
.swiper-slide span{background-size:cover;}
.mod-goods{border-top:1px solid #efeff4; padding:.14rem .1rem;}
.mod-goods ul li{width:50%; padding-bottom:.1rem;}
.goods-item{border:1px solid #efeff4; border-radius:.08rem; margin:0 .05rem;}
.goods-item .bd{width:100%; height:1.5rem; text-align:center; border-bottom:1px solid #efeff4; background-position:50% 50%; background-repeat:no-repeat; background-size:cover;}
.goods-item .ft{padding:.05rem .07rem .08rem;}
.goods-item .ft .tit{font-size:.14rem; line-height:.22rem; height:.44rem;}
.btn-gray{background-color:#999;}
.tit-tips{padding:0 .17rem .1rem; font-size:.12rem;}
.tit-tips em{color:#ffa200;}

.chk-mobile{padding-bottom:20px;}
.chk-mobile .form-item{position:relative;}
.chk-mobile .form-item > p{width:100%; font-size:.12rem; text-align:left; margin-bottom:-.08rem;}
.chk-mobile .form-item{padding:.1rem 0 .05rem;}
.chk-mobile .form-item .weui-input{height:.32rem; background:#ededed; border-radius:.05rem; padding:.05rem;}
.chk-mobile .form-code-item .code-input{padding-right:.9rem; position:relative;}
.form-code-item .weui-btn{position:absolute; right:0; top:.1rem; width:.75rem; height:.32rem; line-height:.32rem; background:#ffa200; color:#fff; border:none; box-shadow:0 0 0;}
.form-code-item .weui-btn.in-disable{background:#d1d1d1;}
</style>
